import React, {
  useState,
  useContext,
  useLayoutEffect,
  useRef,
  useCallback,
} from 'react';
import { View, TouchableOpacity, Keyboard, ScrollView, ImageBackground } from 'react-native';
import { useTranslation } from 'react-i18next';
import { userApi, LoginParams } from '@/services/api/userApi';
import { storage } from '@/utils/storage';
import Checkbox from '@/components/Checkbox';
import { AuthContext } from '@/routes';
import { useNavigation } from '@react-navigation/native';
import Logo from '@/assets/icon/logo.svg';
import DarkLogo from '@/assets/icon/dark-logo.svg';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useForm, Controller } from 'react-hook-form';
import { ErrorText } from '@/components/ErrorText';
import toast from '@/utils/toast';
import { Button, TextInput, Icon, Text, useAppTheme } from 'tsun-smart-ui';
import { useMMKVObject } from '@/hooks/useMMkv';
import { useGetTheme } from '@/hooks/useTheme';
import ActionSheets from '@/components/ActionSheets';
import { BottomSheetModal } from '@gorhom/bottom-sheet';
import DeviceInfo from 'react-native-device-info';
import StringUtils from '@/utils/StringUtils';
import { useDebounceFn } from 'ahooks';

interface LoginResult {
  access_token: string;
  refresh_token: string;
  user_info: {
    userType: 1 | 2;
    [key: string]: any;
  };
  user_id: string;
}

const LoginScreen = () => {
  const { t, i18n } = useTranslation();
  const theme = useAppTheme();
  const currentTheme = useGetTheme();
  const { top } = useSafeAreaInsets();
  const navigation = useNavigation();
  const { setIsLoggedIn, setUserType } = useContext(AuthContext);
  const [loginInfo, setLoginInfo] = useMMKVObject<LoginParams>('loginInfo');
  const bottomSheetModalRef = useRef<BottomSheetModal>(null);
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginParams>({
    defaultValues: loginInfo,
  });
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [agreeToTerms, setAgreeToTerms] = useState(false);
  const tapCount = useRef(0);

  const onPressLogo = useCallback(() => {
    tapCount.current += 1;
    if (tapCount.current >= 10) {
      tapCount.current = 0;
      navigation.navigate('Debugging');
    }
  }, []);

  const { run: debounceLogin } = useDebounceFn(
    (values: LoginParams) => handleLogin(values),
    { wait: 300 }
  );

  // 登录处理
  const handleLogin = async (values: LoginParams) => {
    Keyboard.dismiss();
    try {
      if (!agreeToTerms) {
        toast.showToast({
          message: t('login.termsRequired', {
            defaultValue: '请阅读并同意服务条款和隐私政策',
          }),
        });
        return;
      }
      setLoading(true);
      // 调用登录接口
      const loginParams: LoginParams = {
        username: values.username.trim(),
        password: values.password.trim(),
      };

      const response = await userApi.login(loginParams);
      // 检查返回的数据是否有效
      const loginData = response as unknown as LoginResult;
      // 保存授权信息
      await storage.setAsync('auth_token', loginData.access_token);

      if (loginData.refresh_token) {
        await storage.setAsync('refresh_token', loginData.refresh_token);
      }
      // 缓存用户信息
      if (loginData.user_info) {
        await storage.setAsync(
          'user_info',
          JSON.stringify(loginData.user_info)
        );
      }
      // 获取并缓存用户详细信息
      try {
        const userInfoResponse = await userApi.getUserInfo();
        if (userInfoResponse.code === 0 && userInfoResponse.data) {
          await storage.setAsync(
            'user_info',
            JSON.stringify(userInfoResponse.data)
          );
        }
      } catch (error) {
        console.error('Failed to fetch user info:', error);
      }
      setLoginInfo(rememberMe ? values : undefined);
      // 根据角色类型跳转到不同页面
      const userType = loginData.user_info?.userType || 1;
      setIsLoggedIn?.(true);
      setUserType?.(userType);
    } catch (error) {
      toast.showToast({
        message:
          t(error.message) ||
          t('message.exception', { defaultValue: '网络请求异常，请稍后重试' }),
      });
    } finally {
      setLoading(false);
    }
  };
  useLayoutEffect(() => {
    if (loginInfo) {
      setRememberMe(true);
      setAgreeToTerms(true);
    }
  }, [loginInfo]);
  // 处理服务条款点击
  const handleTermsPress = () => {
    const url = `http://114.55.0.234/private/agreement_${i18n.language}.html`;

    navigation?.navigate('WebView', {
      title: t('sys.termsOfService', { defaultValue: '服务条款' }),
      url,
    });
  };

  // 处理隐私政策点击
  const handlePrivacyPress = () => {
    const url = `http://114.55.0.234/private/privacy_${i18n.language}.html`;

    navigation?.navigate('WebView', {
      title: t('password.privacyPolicy', { defaultValue: '隐私政策' }),
      url,
    });
  };
  // const {visible, options, showActionSheet, hideActionSheet} = useActionSheet();
  const moreOptions = [
    // {
    //   id: 'site',
    //   title: t('user.site_switch'),
    //   onPress: () => {
    //     navigation.navigate('SiteSettings');
    //   },
    // },
    {
      title: t('layout.skin'),
      onPress: () => {
        navigation.navigate('ThemeSettings');
      },
    },
    {
      title: t('settings.language'),
      onPress: () => {
        navigation.navigate('LanguageSettings');
      },
    },
  ];
  const handleShowMore = () => {
    bottomSheetModalRef.current?.present();
  };

  return (
    <ImageBackground source={require('@/assets/imgs/login-bg.png')} className="flex-1">
      <ScrollView
        contentContainerStyle={{ paddingTop: top }}
        className="flex-1"
        scrollEnabled={false}
      >
        <View className="px-6">
          {/* 顶部按钮区域 */}
          <View className="flex-row-reverse pb-9">
            <TouchableOpacity onPress={handleShowMore} className="w-6 h-6 mt-3">
              <Icon
                name="more"
                size={24}
                color={theme.colors?.neutral?.title}
              />
            </TouchableOpacity>
          </View>
          {/* 标题区域 */}
          <View className="items-center" onTouchEnd={onPressLogo}>
            {currentTheme === 'light' ? (
              <Logo width={120} height={100} />
            ) : (
              <DarkLogo width={120} height={100} />
            )}
          </View>
          {/* 登录表单 */}
          <View className="mt-16">
            {/* 用户名输入框 */}
            <Controller
              control={control}
              name="username"
              rules={{
                required: t('sys.app.pls.input.email.or.phone', {
                  defaultValue: '请输入邮箱或手机号',
                }),
                // pattern: {
                //   value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                //   message: t('userSetting.basicInfo.placeholder.email', {
                //     defaultValue: '请输入有效的邮箱地址',
                //   }),
                // },
                validate: (value) => {
                  if (StringUtils.isValidEmail(value) || StringUtils.isValidPhoneNumber(value)) {
                    return true;
                  }
                  return t('sys.app.pls.input.correct.email.or.phone');
                },
              }}
              render={({ field: { onChange, value } }) => (
                <TextInput
                  left="mobile-email"
                  showClearButton
                  keyboardType="email-address"
                  placeholder={t('sys.app.pls.input.email.or.phone', {
                    defaultValue: '请输入邮箱或手机号',
                  })}
                  autoCapitalize="none"
                  onChangeText={onChange}
                  value={value}
                  textContentType="emailAddress"
                />
              )}
            />
            <View className="py-2 ml-14">
              {errors.username && <ErrorText text={errors.username.message!} />}
            </View>
            <Controller
              control={control}
              name="password"
              rules={{
                required: t('login.form.password.placeholder'),
              }}
              render={({ field: { onChange, value } }) => (
                <TextInput
                  left="password"
                  placeholder={t('login.form.password.placeholder', {
                    defaultValue: '请输入密码',
                  })}
                  value={value}
                  onChangeText={onChange}
                  secureTextEntry={!showPassword}
                  textContentType="password"
                  right={
                    <Icon
                      size={16}
                      name={showPassword ? 'eye' : 'eye-off'}
                      onPress={() => setShowPassword(!showPassword)}
                    />
                  }
                />
              )}
            />
            <View className="py-2 ml-14">
              {errors.password && <ErrorText text={errors.password.message!} />}
            </View>
            {/* 记住账号和忘记密码 */}
            <View className=" flex-between flex-row mb-10">
              <Checkbox
                value={rememberMe}
                label={t('login.form.rememberPassword', {
                  defaultValue: '记住账号',
                })}
                onPress={() => {
                  setRememberMe(!rememberMe);
                }}
              />
              <TouchableOpacity
                onPress={() => navigation?.navigate('ResetPassword')}
              >
                <Text style={{ color: theme.colors?.neutral?.secondaryTitle }}>
                  {t('login.form.forgetPassword', { defaultValue: '忘记密码' })}
                </Text>
              </TouchableOpacity>
            </View>

            {/* 服务条款 */}
            <View className="flex-row items-center mb-4">
              <Checkbox
                value={agreeToTerms}
                label={
                  <>
                    <Text style={{ color: theme.colors?.neutral?.title }}>
                      {t('password.i_have_read_it', {
                        defaultValue: '我已阅读并同意',
                      })}
                      <Text
                        style={{ color: theme.colors?.info?.primary }}
                        onPress={handleTermsPress}
                      >
                        {' ' +
                          t('sys.termsOfService', {
                            defaultValue: '服务条款',
                          }) +
                          ' '}
                      </Text>
                      {t('password.and.tip', { defaultValue: '和' })}
                      <Text
                        style={{ color: theme.colors?.info?.primary }}
                        onPress={handlePrivacyPress}
                      >
                        {' ' +
                          t('password.privacyPolicy', {
                            defaultValue: '隐私政策',
                          })}
                      </Text>
                    </Text>
                  </>
                }
                onPress={() => setAgreeToTerms(!agreeToTerms)}
              />
            </View>

            {/* 登录按钮 */}
            <Button
              loading={loading}
              disabled={loading}
              title={t('staticRoutes.login', { defaultValue: '登录' })}
              onPress={handleSubmit(debounceLogin)}
            ></Button>
            {/* 其他登录选项 */}
            <View className="flex-row justify-center px-8">
              <TouchableOpacity
                className="mt-12 flex-row items-center"
                onPress={() => navigation?.navigate('Register')}
              >
                <Text style={{ color: theme.colors?.neutral?.secondaryTitle }}>
                  {t('common.noaccount') + ' '}
                </Text>
                <Text style={{ color: theme.colors?.brand?.primary }}>
                  {t('user.registerImmediately', { defaultValue: '立即注册' })}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        <Text className="text-center text-[8px] mt-6" style={{ color: '#CCC' }}>
          {DeviceInfo.getVersion()}（{DeviceInfo.getBuildNumber()}）
        </Text>
      </ScrollView>
      <ActionSheets
        options={moreOptions}
        ref={bottomSheetModalRef}
      ></ActionSheets>
    </ImageBackground>
  );
};

export default LoginScreen;
